package com.example.exceptionHandle;

import com.example.entity.MyResponseEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @author fyxw
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandle {
    /**
     * 捕捉参数校验异常，封装到json中，返回给用户
     * @param e 捕捉到的参数校验异常
     * @return 封装json对象
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public MyResponseEntity<?> validExceptionHandle(MethodArgumentNotValidException e) {
        StringBuilder sb = new StringBuilder();
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        allErrors.forEach(error -> sb.append(error.getDefaultMessage()).append(";"));
        log.debug(sb.toString());
        return new MyResponseEntity<>(400, sb.toString(), null);
    }

    @ExceptionHandler(Exception.class)
    public MyResponseEntity<?> defaultException(Exception e) {
        log.warn("异常原因: "+e.getMessage());
        return new MyResponseEntity<>(500, "服务器维护中", null);
    }

    @ExceptionHandler(UnauthorizedException.class)
    public MyResponseEntity<?> unauthorizedExceptionHandle(UnauthorizedException e) {
        return new MyResponseEntity<>(401, "无权限访问此资源", null);
    }

}
